package com.example.demo.api;


import com.example.demo.model.Result;
import com.example.demo.model.User;
import com.example.demo.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/api/user")
public class UserAPI {
    @Autowired
    private UserService userService;

    /**
     * 用户注册
     * @param userName 用户名
     * @param pwd 密码
     * @return
     */
    @PostMapping("/register")
    @ResponseBody
    public Result<User> register(@RequestParam("userName") String userName, @RequestParam("pwd") String pwd) {
        return userService.register(userName, pwd);
    }

    /**
     * 用户登录
     * @param userName 用户名
     * @param pwd 密码
     * @param request Http请求对象
     * @return
     */
    @PostMapping("login")
    @ResponseBody
    public Result<User> login(@RequestParam("userName") String userName, @RequestParam("pwd") String pwd, HttpServletRequest request) {
        Result<User> result = userService.login(userName, pwd);
        if (result.isSuccess()) {
            request.getSession().setAttribute("userId", result.getData().getId());
        }
        return result;
    }

    /**
     * 用户注销
     * @param request Http请求对象
     * @return
     */
    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpServletRequest request) {
        Result result = new Result();
        request.getSession().removeAttribute("userId");
        result.setSuccess(true);
        return result;
    }

    /**
     * 判断用户是否登录
     * @param request
     * @return
     */
    @GetMapping("/checklogin")
    @ResponseBody
    public Result checkLogin(HttpServletRequest request) {
        Result result = new Result();
        if (request.getSession().getAttribute("userId")==null){
            result.setData(false);
            result.setMessage("用户未登录");
        }else {
            result.setData(true);
            result.setMessage("用户已登录");
        }
        result.setSuccess(true);
        return result;
    }
}
